# coding=utf-8

import json
import urllib2

API = 'https://api.seniverse.com/v3/weather/daily.json?{}'


def get_days_weather(days=1, location='chengdu', language='zh-Hans', start=0, key='opmc13gzz833wulw'):
    query_string = 'key={}&location={}&language={}&start={}&days={}'.format(
        key, location, language, start, days
    )
    url = API.format(query_string)
    try:
        resp = urllib2.urlopen(url, timeout=5)
        data = resp.read()
        result = json.loads(data)
        daily = result.get('results')[0].get('daily')
        return daily[0]
    # "daily": [
    #     {
    #         "date": "2018-03-06",
    #         "text_day": "小雨",
    #         "code_day": "13",
    #         "text_night": "小雨",
    #         "code_night": "13",
    #         "high": "11",
    #         "low": "8",
    #         "precip": "",
    #         "wind_direction": "无持续风向",
    #         "wind_direction_degree": "",
    #         "wind_speed": "10",
    #         "wind_scale": "2"
    #     }
    # ]
    except Exception as e:
        print (e)


def chinese2word(weather):
    if u'雨' in weather:
        return 'rainy'
    elif u'云' in weather:
        return 'cloudy'
    elif u'雪' in weather:
        return 'snowy'
    elif u'风' in weather:
        return ''
    elif u'雷' in weather:
        return 'stormy'
    elif u'晴' in weather:
        return 'sunny'
    elif u'彩虹' in weather:
        return 'rainbow'
